package Fisica.ArticulosStock;

import java.io.Closeable;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import Fisica.SessionFactoryUtil;
import Modelo.Articulo;

public abstract class ABMArticulosFisica {
	
	public static String _PRE = "from Articulo as c where c.id < ? order by c.id desc  ";
	public static String _POS = "from Articulo as c where c.id > ? order by c.id asc";
	public static String _FIRST = "select a from Articulo as a where a.id = (select min(c.id) as max from Articulo as c)";
	public static String _LAS = "select a from Articulo as a where a.id = (select max(c.id) as max from Articulo as c)";
	public static String _BYID = "from Articulo as a where a.id = ?";
	public static String _BYBARRA = "from Articulo as a where a.idCodBar = ?";
	
	public static String _BYNOMBRE = "from Articulo as c where c.nombre = ?";
	public static String _BYRUBRO = "select a from Articulo as a, Rubros as r where a.idRubros = r.id and r.nombre = ?";
	
	public static String _LISTAR = "from Articulo as o order by o.id asc";
	public static String _LISTARNOMBRES = "from Articulo as o where o.nombre LIKE :str order by o.id asc";
	public static String _SELECT_COUNT = "select count(*) ";
	
	//Busca un Articulo a partir de un identificador OK
    public static Articulo findById(Integer id) {
  	try {
  			SessionFactory sessionFactory = SessionFactoryUtil.getSessionFactory();
			Session session = sessionFactory.getCurrentSession();
	    	Transaction transaction = session.beginTransaction();
	                
	        Query query = session.createQuery(_BYID).setInteger(0, id);
	        query.setFetchSize(3);
	        Iterator iter = query.iterate();
			
			Articulo obj = new Articulo();
			if ( iter.hasNext() ) {
				obj = (Articulo) iter.next();  // fetch the object
			}
				        
			return obj;
	
	       }catch (RuntimeException re) {
				System.out.println("get failed: "+re);
				throw re;
			}
   }
    
  //Busca un Articulo a partir de un codigo de barra OK
    public static Articulo findByBarra(String barra) {
  	try {
  			SessionFactory sessionFactory = SessionFactoryUtil.getSessionFactory();
			Session session = sessionFactory.getCurrentSession();
	    	Transaction transaction = session.beginTransaction();
	                
	        Query query = session.createQuery(_BYBARRA).setString(0, barra);
	        query.setFetchSize(3);
	        Iterator iter = query.iterate();
			
			Articulo obj = new Articulo();
			if ( iter.hasNext() ) {
				obj = (Articulo) iter.next();  // fetch the object
			}
				        
			return obj;
	
	       }catch (RuntimeException re) {
				System.out.println("get failed: "+re);
				throw re;
			}
   }
    
    
    
  //Busca un Articulo a partir de un objeto Articulo OK
	public static Articulo find(Articulo c) {
		return ABMArticulosFisica.findById(c.getId());
    }
    
  //Busca un Articulo a partir de un identificador OK
    public static Articulo findByNombre(String ap) {
    	try {
    		SessionFactory sessionFactory = SessionFactoryUtil.getSessionFactory();
  			Session session = sessionFactory.getCurrentSession();
	    	Transaction transaction = session.beginTransaction();
	                
	        Query query = session
	        .createQuery("from Articulo as c where c.nombre = '"+ap+"'");

	        query.setFetchSize(20);
	        Iterator iter = query.iterate();
			
			Articulo obj = new Articulo();
			if ( iter.hasNext() ) {
				return (Articulo) iter.next();
			}
			
			return obj;
			
	       }catch (RuntimeException re) {
				System.out.println("get failed: "+re);
				throw re;
			}
   }
    
    public static int countByNombre(String ap) {
    	try {
    		SessionFactory sessionFactory = SessionFactoryUtil.getSessionFactory();
  			Session session = sessionFactory.getCurrentSession();
	    	Transaction transaction = session.beginTransaction();
	                
	        Query query = session
	        .createQuery( _BYNOMBRE).setString(0, ap);
	        int count = query.list().size();
	
	        return count; 	        
	        
	       }catch (RuntimeException re) {
				re.printStackTrace();
				throw re;
			}
   }
    
    public static List<Articulo> getListByRubro(String str) {
    	try {
    		SessionFactory sessionFactory = SessionFactoryUtil.getSessionFactory();
  			Session session = sessionFactory.getCurrentSession();
	    	Transaction transaction = session.beginTransaction();
	                
	        Query query = session
	        .createQuery(_BYRUBRO).setString(0, str);
	        List<Articulo> list = query.list();
	
	        return list; 	        
	       }catch (RuntimeException re) {
				re.printStackTrace();
				throw re;
			}
   }
    
  //Busca un Articulo anterior a partir de un identificador OK
    public static Articulo get(String script, Integer id) {
    	try {
    		SessionFactory sessionFactory = SessionFactoryUtil.getSessionFactory();
  			Session session = sessionFactory.getCurrentSession();
	    	Transaction transaction = session.beginTransaction();
	                
	        Query query = session.createQuery(script).setInteger(0, id);
	        query.setFetchSize(3);
	        Iterator iter = query.iterate();
			
			Articulo obj = new Articulo();
			if ( iter.hasNext() ) {
				obj = (Articulo) iter.next();  // fetch the object
			}

			return obj;
	       }catch (RuntimeException re) {
				System.out.println("get failed: "+re);
				throw re;
			}
   }
    
  //Busca un Articulo anterior a partir de un identificador OK
    public static Articulo get(String script) {
    	try {
    		SessionFactory sessionFactory = SessionFactoryUtil.getSessionFactory();
  			Session session = sessionFactory.getCurrentSession();
	    	Transaction transaction = session.beginTransaction();
	                
	        Query query = session.createQuery(script);
	        query.setFetchSize(3);
	        Iterator iter = query.iterate();		
	        
			Articulo obj = new Articulo();
			if ( iter.hasNext() ) {
				obj = (Articulo) iter.next();  // fetch the object
			}
			
	        
			return obj;
			
	       }catch (RuntimeException re) {
				System.out.println("get failed: "+re);
				throw re;
			}
   }
    
//  Busca un Articulo posterior a partir de un identificador OK
    public static Articulo getPos(Integer id) {
    	try {
    		return get(_POS, id);
       }catch (RuntimeException re) {
				System.out.println("get failed: "+re);
				throw re;
			}
   }
    
    public static Articulo getPre(Integer id) {
    	try {
    		return get(_PRE, id);
	       }catch (RuntimeException re) {
				System.out.println("get failed: "+re);
				throw re;
			}
   }
    
    public static Articulo getFirst(){
    	try {
    		return get(_FIRST);
       }catch (RuntimeException re) {
				System.out.println("get failed: "+re);
				throw re;
			}
    }
    
  //Busca el ultimo Articulo  OK
    public static Articulo getLast() {
    	try {
    		return get(_LAS);
       }catch (RuntimeException re) {
				System.out.println("get failed: "+re);
				throw re;
			}
   }
    
  //Busca un Articulo a partir de un identificador OK
    public static List<Articulo> list() {
    	try {
    		SessionFactory sessionFactory = SessionFactoryUtil.getSessionFactory();
  			Session session = sessionFactory.getCurrentSession();
	    	Transaction transaction = session.beginTransaction();
		                
		    Query query = session.createQuery(_LISTAR);
		    List<Articulo> list = query.list();
		        
		
		    return list;	 
    	}catch (RuntimeException re) {
			System.out.println("get failed: "+re);
			throw re;
		}
   }
    
  //Busca un Articulo a partir de un identificador OK
    public static List<Articulo> list(String str) {
    	try {
    		SessionFactory sessionFactory = SessionFactoryUtil.getSessionFactory();
  			Session session = sessionFactory.getCurrentSession();
	    	Transaction transaction = session.beginTransaction();
		                
		    Query query = session.createQuery(_LISTARNOMBRES).setString("str", "%" + str + "%");
		    List<Articulo> list = query.list();
		     
//		    if(!SessionFactoryUtil.getSessionFactory().isClosed()){
//	        	SessionFactoryUtil.getSessionFactory().close();
//	        }
//	       session.getTransaction().commit();
//		    session.getTransaction().commit(); //Como ya se ha hecho la consulta, hago commit. 
//		        								   //El commit cierra automnticamente la session.
//		    SessionFactoryUtil.getSessionFactory().close();
		
		    return list;	 
    	}catch (RuntimeException re) {
			System.out.println("get failed: "+re);
			throw re;
		}
   }
    
  //Agrego un Articulo a la base OK
	public static void add(Articulo c) {
		try{
			SessionFactory sessionFactory = SessionFactoryUtil.getSessionFactory();
  			Session session = sessionFactory.getCurrentSession();
	        Transaction transaction = session.beginTransaction();
	        //chekeo que el Articulo no exista para agregarlo
	        Query query = session
	        		.createQuery(_BYNOMBRE).setString(0, c.getNombre());
	        List<ABMArticulosFisica> list = query.list();
	
	        if (list.isEmpty())
	        {
	        	session.save(c);
	        	System.out.println("Articulo agregado con exito!!!");
	        }
	        
	         //Como ya se ha hecho la consulta, hago commit. 
	        								   //El commit cierra automnticamente la session.
//	        if(!SessionFactoryUtil.getSessionFactory().isClosed()){
//	        	SessionFactoryUtil.getSessionFactory().close();
//	        }
//	        session.getTransaction().commit();
	        
	        if(!sessionFactory.isClosed()){
	        	sessionFactory.close();
	        }
	        transaction.commit();
	        
		}catch (RuntimeException re) {
				System.out.println("get failed: "+re);
				throw re;
			}
	}
	
	//Actualizacion de un Articulo OK
	public static void update(Articulo c) {
		try{
			SessionFactory sessionFactory = SessionFactoryUtil.getSessionFactory();
  			Session session = sessionFactory.getCurrentSession();
	        Transaction transaction = session.beginTransaction();
	        
	        if (c.getId() != 0) {
	        	session.update(c);
	            System.out.println("Articulo actualizado con exito!!!");
	        }
	               
//	        session.getTransaction().commit(); //Como ya se ha hecho la consulta, hago commit. El commit cierra automnticamente la session.
//	        SessionFactoryUtil.getSessionFactory().close();
	        
	        if(!sessionFactory.isClosed()){
	        	sessionFactory.close();
	        }
	        transaction.commit();
	        
		}catch (RuntimeException re) {
				System.out.println("get failed: "+re);
				throw re;
			}
    }
	
}
